package com.Eric.BBSM.Servlet;

import com.Eric.BBSM.JavaBean.DataBean.User;
import com.Eric.BBSM.Service.UserService;
import com.Eric.BBSM.Service.implement.UserServiceImplement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.PageContext;
import java.io.IOException;

/**
 * @author Eric
 * @Create 2020-09-01  20:36
 * @Version Demo
 **/
@WebServlet("/UserServlet")
public class UserServlet extends BaseServlet {

    private UserService userService = new UserServiceImplement();

    protected void regist(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //1.获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String userSex = request.getParameter("sex");
        String userEmail = request.getParameter("userEmail");
        String userTel = request.getParameter("userTel");

        //2.调用Service方法
        Boolean checkRegist = userService.checkRegist(username, password);
        User user = new User(username, password, userSex, userEmail, userTel);

        if (!checkRegist) {
            //用户名可用
            //1.存到数据库
            Integer regist = userService.regist(user);

            //2.跳转 登录页面 /before-pages/user/login.jsp
            response.sendRedirect(request.getContextPath() + "/before-pages/user/login.jsp");
        } else {
            //用户名不可用
            //跳转回注册页面
            request.setAttribute("regist", "false");
            request.getRequestDispatcher("/before-pages/user/regist.jsp").forward(request, response);
        }

    }

    protected void login(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        //1.获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //2.调用Service层方法
        User user = userService.getUser(username, password);
        System.out.println("user = " + user);
        if (user != null) {
            //登陆成功！
            //3.将用户信息存放到域中
            session.setAttribute("user", user);
            //4.跳转到主页面 index.jsp
            response.sendRedirect(request.getContextPath() + "/index.jsp");
        } else {
            //登陆失败！
            //4.跳转回登录页面
            response.sendRedirect(request.getContextPath() + "/before-pages/user/login.jsp");
        }

    }

    protected void logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        session.removeAttribute("user");
        response.sendRedirect(request.getContextPath()+"/index.jsp");
    }

}
